package com.ruoyi.phd.controller;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.phd.domain.PhdInformation;
import com.ruoyi.phd.service.IPhdInformationService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.excel.EasyExcel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.phd.listener.PhdExcelListener;

@RestController
@RequestMapping("/information/manage")
public class PhdInformationController extends BaseController
{
    @Autowired
    private IPhdInformationService phdInformationService;
    private static final Logger log = LoggerFactory.getLogger(PhdInformationController.class);
    /**
     * 查询Manage列表
     */
    @PreAuthorize("@ss.hasPermi('information:manage:list')")
    @GetMapping("/list")
    public TableDataInfo list(PhdInformation phdInformation)
    {
        startPage();
        List<PhdInformation> list = phdInformationService.selectPhdInformationList(phdInformation);
        return getDataTable(list);
    }

    /**
     * 导出Manage列表
     */
    @PreAuthorize("@ss.hasPermi('information:manage:export')")
    @Log(title = "Manage", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PhdInformation phdInformation)
    {
        List<PhdInformation> list = phdInformationService.selectPhdInformationList(phdInformation);
        ExcelUtil<PhdInformation> util = new ExcelUtil<PhdInformation>(PhdInformation.class);
        util.exportExcel(response, list, "Manage数据");
    }

    /**
     * 获取Manage详细信息
     */
    @PreAuthorize("@ss.hasPermi('information:manage:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(phdInformationService.selectPhdInformationById(id));
    }

    /**
     * 新增Manage
     */
    @PreAuthorize("@ss.hasPermi('information:manage:add')")
    @Log(title = "Manage", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PhdInformation phdInformation)
    {
        return toAjax(phdInformationService.insertPhdInformation(phdInformation));
    }

    /**
     * 修改Manage
     */
    @PreAuthorize("@ss.hasPermi('information:manage:edit')")
    @Log(title = "Manage", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PhdInformation phdInformation)
    {
        return toAjax(phdInformationService.updatePhdInformation(phdInformation));
    }

    /**
     * 删除Manage
     */
    @PreAuthorize("@ss.hasPermi('information:manage:remove')")
    @Log(title = "Manage", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(phdInformationService.deletePhdInformationByIds(ids));
    }
    /**
     * 上传Excel文件并导入博士信息
     * @param file 前端上传的Excel文件
     * @return 导入结果
     */
    @PreAuthorize("@ss.hasPermi('information:manage:import')") // 新增导入权限
    @PostMapping("/import")
    public AjaxResult importExcel(MultipartFile file) {
        // 1. 校验文件是否为空
        if (file.isEmpty()) {
            return AjaxResult.error("上传的Excel文件不能为空");
        }

        try {
            // 2. 用EasyExcel读取文件：指定文件流、实体类、监听器
            EasyExcel.read(
                            file.getInputStream(), // Excel文件输入流
                            PhdInformation.class,  // 读取后映射的实体类（需与Excel列名对应）
                            new PhdExcelListener(phdInformationService) // 自定义监听器（注入服务层）
                    ).sheet() // 读取第一个工作表（默认读取第1个，可指定sheetName或sheetNo）
                    .doRead(); // 开始读取

            // 3. 读取+插入成功，返回结果
            return AjaxResult.success("Excel数据导入成功");
        } catch (IOException e) {
            log.error("Excel文件读取失败", e);
            return AjaxResult.error("Excel文件读取失败：" + e.getMessage());
        } catch (RuntimeException e) {
            log.error("Excel数据导入失败", e);
            return AjaxResult.error("数据导入失败：" + e.getMessage());
        }
    }
    /**
     * 下载导入模板
     */
    @PreAuthorize("@ss.hasPermi('information:manage:import')")
    @GetMapping("/importTemplate")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        // 创建一个新的Excel工作簿
        Workbook workbook = phdInformationService.createImportTemplate();

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        String fileName = URLEncoder.encode("博士信息导入模板.xlsx", "UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        // 将工作簿写入响应输出流
        try (OutputStream outputStream = response.getOutputStream()) {
            workbook.write(outputStream);
            outputStream.flush();
        } finally {
            workbook.close();
        }
    }
    @PreAuthorize("@ss.hasPermi('information:manage:edit')") // 确保有相应权限才能调用
    @PostMapping("/reorderIds")
    public AjaxResult reorderIds() {
        try {
            phdInformationService.reorderIds();
            return AjaxResult.success("ID 重新整理成功");
        } catch (Exception e) {
            return AjaxResult.error("ID 重新整理失败：" + e.getMessage());
        }
    }
}

